import * as React from 'react';
import classNames from 'classnames';

import { BaseProps, BaseHelper } from '../base';

const rxTwoCNChar = /^[\u4e00-\u9fa5]{2}$/;
const isTwoCNChar = rxTwoCNChar.test.bind(rxTwoCNChar);
function isString(str: any) {
  return typeof str === 'string';
}

function insertSpace(child: React.ReactChild, needInserted: boolean) {
  // Check the child if is undefined or null.
  if (child === null) {
    return;
  }
  const SPACE = needInserted ? ' ' : '';
  // strictNullChecks oops.
  if (
    typeof child !== 'string' &&
    typeof child !== 'number' &&
    isString(child.type) &&
    isTwoCNChar(child.props.children)
  ) {
    return React.cloneElement(child, {}, child.props.children.split('').join(SPACE));
  }
  let _child: string;
  if (typeof child === 'string') {
    if (isTwoCNChar(child)) {
      _child = child.split('').join(SPACE);
      return _child;
    }
    return <span>{child}</span>;
  }
  return child;
}

// 传入组件的属性规约
export type ButtonProps = {
  onClick?: React.MouseEventHandler<HTMLElement>;
} & BaseProps & Omit<React.ButtonHTMLAttributes<any>, 'type' | 'onClick'>;

// TypeScript的无状态组件的写法
const Button: React.SFC<ButtonProps> = (props: ButtonProps) => {

  let _style = BaseHelper.concatStyle(props);
  const prefixClass = BaseHelper.getPrefixCls('button');

  let rest = BaseHelper.omit(props as ButtonProps)

  console.log(rest, '======rest=======')

  if (props.height) {
    _style = {
      ..._style,
      lineHeight: props.height + 'px'
    }
  }

  const wrapCls = classNames(
    {
      [`${prefixClass}`]: true,
    },
    props.className
  );

  return (
    <button
      className={wrapCls}
      style={_style}

      {...rest}

      onClick={(e) => { !props.disabled && props.onClick && !props.disabled && props.onClick(e); }}
    >
      {
        props.children && insertSpace(props.children, true)
      }

    </button>
  );

}

export default Button;
